<script setup lang="ts">
import { ref, reactive, h, onMounted } from "vue";
import { DynamicTable } from "@/components/DynamicTable";
import { PaginationConfig, TableColumn } from "@/components/DynamicTable/types";
import DynamicForm from "@/components/DynamicForm/index.vue";
import type { DynamicFormInstance } from "@/components/DynamicForm/types";
import { FormItemConfig } from "@/components/DynamicForm/types";
import { ElMessage, ElMessageBox, ElTag } from "element-plus";
import { Refresh } from "@element-plus/icons-vue";
import { getBeianList, getBeianDetail, deleteBeian } from "../servers";

const props = defineProps<{
  task: string;
}>();

const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 20,
  total: 0,
  pageSizes: [20, 50, 100],
  layout: "total, sizes, prev, pager, next",
  background: true,
});

const beianList = ref([]);
const loading = ref(false);
const searchFormRef = ref<DynamicFormInstance>();

const searchForm = reactive({
  type: "",
  keyword: "",
});

const searchConfig: FormItemConfig[] = [
  {
    key: "type",
    name: "备案类型",
    type: "select",
    placeholder: "选择备案类型",
    col: { span: 4 },
    params: {
      clearable: true,
      showPlaceholder: false,
      options: [
        { label: "全部", value: "" },
        { label: "网站域名(web)", value: "web" },
        { label: "移动应用(app)", value: "app" },
        { label: "微信小程序(mapp)", value: "mapp" },
      ],
    },
  },
  {
    key: "keyword",
    name: "关键词",
    type: "input",
    placeholder: "搜索域名/单位名称/备案号",
    col: { span: 6 },
    params: {
      clearable: true,
    },
  },
];

const columns = ref<TableColumn[]>([
  {
    label: "域名",
    prop: "domain",
    minWidth: 200,
    show: true,
  },
  {
    label: "主办单位",
    prop: "unit_name",
    minWidth: 200,
    show: true,
  },
  {
    label: "主体备案号",
    prop: "main_licence",
    width: 180,
    show: true,
  },
  {
    label: "服务备案号",
    prop: "service_licence",
    width: 180,
    show: true,
  },
  {
    label: "备案类型",
    prop: "record_type",
    width: 120,
    show: true,
    render: (row) => {
      const typeMap = {
        web: { text: "网站", type: "info" },
        app: { text: "移动应用", type: "success" },
        mapp: { text: "微信小程序", type: "warning" },
      };
      const item = typeMap[row.record_type] || {
        text: row.record_type,
        type: "",
      };
      return h(ElTag, { type: item.type, size: "small" }, () => item.text);
    },
  },
  {
    label: "单位性质",
    prop: "nature_name",
    width: 120,
    show: true,
  },
  {
    label: "内容类型",
    prop: "content_type_name",
    width: 120,
    show: true,
  },
  {
    label: "记录时间",
    prop: "update_record_time",
    width: 120,
    show: true,
  },
  {
    label: "创建时间",
    prop: "created_at",
    width: 160,
    show: true,
  },
  {
    label: "操作",
    prop: "action",
    width: 180,
    show: true,
    slot: "action",
    fixed: "right",
  },
]);

// 备案详情对话框
const detailDialogVisible = ref(false);
const beianDetail = ref<any>(null);

const fetchBeianList = async () => {
  loading.value = true;
  try {
    const params: any = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      ...searchForm,
    };
    // 移除空值
    Object.keys(params).forEach((key) => {
      if (
        params[key] === "" ||
        params[key] === null ||
        params[key] === undefined
      ) {
        delete params[key];
      }
    });
    const { data } = await getBeianList(params);
    beianList.value = data.list || [];
    pagination.total = data.total || 0;
  } catch (error) {
    ElMessage.error("获取备案列表失败");
  } finally {
    loading.value = false;
  }
};

const handleSearch = (value: any) => {
  searchForm.type = value.type || "";
  searchForm.keyword = value.keyword || "";
  pagination.currentPage = 1;
  fetchBeianList();
};

const handleSearchReset = () => {
  searchFormRef.value?.resetFields();
  searchForm.type = "";
  searchForm.keyword = "";
  pagination.currentPage = 1;
  fetchBeianList();
};

const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  fetchBeianList();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchBeianList();
};

const handleViewDetail = async (row: any) => {
  try {
    const { data } = await getBeianDetail({ id: row.id });
    beianDetail.value = data;
    detailDialogVisible.value = true;
  } catch (error) {
    ElMessage.error("获取备案详情失败");
  }
};

const handleDelete = (row: any) => {
  ElMessageBox.confirm("确定删除该备案域名吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      await deleteBeian({ id: row.id });
      ElMessage.success("删除成功");
      fetchBeianList();
    } catch (error) {
      ElMessage.error("删除失败");
    }
  });
};

onMounted(() => {
  fetchBeianList();
});
</script>

<template>
  <div>
    <!-- 搜索表单 -->
    <el-card shadow="never">
      <div class="search-form-container">
        <DynamicForm
          ref="searchFormRef"
          v-model="searchForm"
          :form-config="searchConfig"
          :gutter="16"
          label-width="100px"
          type="search"
          @search="handleSearch"
          @reset="handleSearchReset"
        />
      </div>
    </el-card>

    <div style="height: 10px"></div>

    <el-card>
      <DynamicTable
        :pagination="pagination"
        :columns="columns"
        :data="beianList"
        :loading="loading"
        @current-page-change="handlePageChange"
        @size-change="handleSizeChange"
      >
        <template #toolbar-right>
          <el-button type="success" :icon="Refresh" @click="fetchBeianList">
            刷新
          </el-button>
        </template>

        <template #action="{ row }">
          <el-button type="info" size="small" @click="handleViewDetail(row)">
            详情
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </DynamicTable>
    </el-card>

    <!-- 备案详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="备案详情"
      width="900px"
      destroy-on-close
    >
      <el-descriptions v-if="beianDetail" :column="2" border>
        <el-descriptions-item label="域名">{{
          beianDetail.domain
        }}</el-descriptions-item>
        <el-descriptions-item label="备案类型">
          <el-tag
            :type="
              beianDetail.record_type === 'web'
                ? 'info'
                : beianDetail.record_type === 'app'
                ? 'success'
                : 'warning'
            "
            size="small"
          >
            {{
              beianDetail.record_type === "web"
                ? "网站"
                : beianDetail.record_type === "app"
                ? "移动应用"
                : "微信小程序"
            }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="主办单位">{{
          beianDetail.unit_name
        }}</el-descriptions-item>
        <el-descriptions-item label="主体备案号">{{
          beianDetail.main_licence
        }}</el-descriptions-item>
        <el-descriptions-item label="服务备案号">{{
          beianDetail.service_licence || "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="单位性质">{{
          beianDetail.nature_name
        }}</el-descriptions-item>
        <el-descriptions-item label="内容类型">{{
          beianDetail.content_type_name
        }}</el-descriptions-item>
        <el-descriptions-item label="记录时间">{{
          beianDetail.update_record_time || "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="负责人">{{
          beianDetail.leader_name || "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="是否限制接入">{{
          beianDetail.limit_access || "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="主办单位地址" :span="2">{{
          beianDetail.main_unit_address || "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="子域名数量">{{
          beianDetail.subdomain_count || 0
        }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{
          beianDetail.created_at
        }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{
          beianDetail.updated_at || "-"
        }}</el-descriptions-item>
      </el-descriptions>

      <!-- 原始数据 (如果有) -->
      <div v-if="beianDetail.raw_data" style="margin-top: 20px">
        <el-card shadow="never">
          <template #header>
            <strong>原始数据</strong>
          </template>
          <pre
            style="
              background: #f5f7fa;
              padding: 16px;
              border-radius: 4px;
              overflow-x: auto;
            "
            >{{ JSON.stringify(beianDetail.raw_data, null, 2) }}</pre
          >
        </el-card>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.search-form-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}
</style>
